package com.ddxz.csms.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2021/11/20
 */

@Configuration
@MapperScan(basePackages = "com.ddxz.csms.mapper.base", sqlSessionTemplateRef = "baseSessionTemplate")
public class BaseInfoMySQLConfig {
    @Bean("baseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.base")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean("baseMysqlSessionFactory")
    public SqlSessionFactory baseMysqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/base/BaseInfoMapper.xml"));
        return factoryBean.getObject();
    }

    @Bean("baseTranscationManager")
    public DataSourceTransactionManager baseTranscationManager(@Qualifier("baseDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("baseSessionTemplate")
    public SqlSessionTemplate baseSessionTemplate(@Qualifier("baseMysqlSessionFactory") SqlSessionFactory factory) {
        return new SqlSessionTemplate(factory);
    }
}
